using System.IO;
using System.Text.RegularExpressions;
using System.Web.Hosting;
using Toast.Core;
using Toast.Core.Interfaces;
using Toast.Extensions;
using Toast.Utils;

namespace Toast.ContentTypes
{
    public sealed class LocalCssFile : CssContentBase, ICompressable
    {
        readonly string _fullPath;

        public LocalCssFile()
        {
        }

        internal LocalCssFile(string filePath, InjectAt injectAt, ICompressionStrategy compression)
        {
            OriginalPath = Utility.CleanPath(filePath);
            InjectAt = injectAt;
            FileName = Path.GetFileName(filePath);
            Compression = compression;
            _fullPath = HostingEnvironment.MapPath(OriginalPath);
        }

        public string OriginalPath { get; set; }
        public string Content { get; set; }

        public string FullPath
        {
            get { return _fullPath; }
        }
        
        public string ToEncodedUrl(string pathFormat, string packageKey)
        {
            return pathFormat.FormatWith(EncodingUtils.UrlSafeEncode(Id.ToString()), packageKey);
        }

        public override bool TryConstructFrom(string from, out IContent result)
        {
            if (!Regex.IsMatch(from, @"^[\\/\a-zA-Z\-][^\:]+css"))
            {
                result = null;
                return false;
            }

            var orignalPath = from;
            result = new LocalCssFile(orignalPath, InjectAt.Default, ToastCore.Compression().ForCss());

            return true;
        }

        public override IInjectionFormatter GetFormatter(string packageKey)
        {
            return new LocalFileFormatter(packageKey, "<link rel='stylesheet' href='{0}' />");
        }


    }
}